/**
 * 缓存服务
 * 处理数据缓存相关业务逻辑
 */

import { CACHE, STORAGE_KEYS } from '@/constants'

export class CacheService {
  /**
   * 设置缓存
   */
  static setCache<T>(key: string, data: T, ttl?: number): void {
    try {
      const cacheData = {
        data,
        timestamp: Date.now(),
        ttl: ttl || CACHE.USER_INFO_TTL
      }
      
      localStorage.setItem(key, JSON.stringify(cacheData))
    } catch (error) {
      console.error('设置缓存失败:', error)
    }
  }

  /**
   * 获取缓存
   */
  static getCache<T>(key: string): T | null {
    try {
      const cached = localStorage.getItem(key)
      if (!cached) return null

      const cacheData = JSON.parse(cached)
      
      // 检查是否过期
      if (Date.now() - cacheData.timestamp > cacheData.ttl) {
        localStorage.removeItem(key)
        return null
      }

      return cacheData.data
    } catch (error) {
      console.error('获取缓存失败:', error)
      return null
    }
  }

  /**
   * 删除缓存
   */
  static removeCache(key: string): void {
    try {
      localStorage.removeItem(key)
    } catch (error) {
      console.error('删除缓存失败:', error)
    }
  }

  /**
   * 清空所有缓存
   */
  static clearAllCache(): void {
    try {
      const keys = Object.values(STORAGE_KEYS)
      keys.forEach(key => {
        localStorage.removeItem(key)
      })
    } catch (error) {
      console.error('清空缓存失败:', error)
    }
  }

  /**
   * 检查缓存是否存在且未过期
   */
  static hasCache(key: string): boolean {
    try {
      const cached = localStorage.getItem(key)
      if (!cached) return false

      const cacheData = JSON.parse(cached)
      return Date.now() - cacheData.timestamp <= cacheData.ttl
    } catch (error) {
      console.error('检查缓存失败:', error)
      return false
    }
  }

  /**
   * 获取缓存剩余时间（毫秒）
   */
  static getCacheTTL(key: string): number {
    try {
      const cached = localStorage.getItem(key)
      if (!cached) return 0

      const cacheData = JSON.parse(cached)
      const remaining = cacheData.ttl - (Date.now() - cacheData.timestamp)
      return Math.max(0, remaining)
    } catch (error) {
      console.error('获取缓存TTL失败:', error)
      return 0
    }
  }

  /**
   * 设置用户信息缓存
   */
  static setUserInfoCache<T>(data: T): void {
    this.setCache(STORAGE_KEYS.USER_INFO, data, CACHE.USER_INFO_TTL)
  }

  /**
   * 获取用户信息缓存
   */
  static getUserInfoCache<T>(): T | null {
    return this.getCache<T>(STORAGE_KEYS.USER_INFO)
  }

  /**
   * 设置菜单列表缓存
   */
  static setMenuListCache<T>(data: T): void {
    this.setCache(STORAGE_KEYS.USER_INFO, data, CACHE.MENU_LIST_TTL)
  }

  /**
   * 获取菜单列表缓存
   */
  static getMenuListCache<T>(): T | null {
    return this.getCache<T>(STORAGE_KEYS.USER_INFO)
  }

  /**
   * 设置系统设置缓存
   */
  static setSettingsCache<T>(data: T): void {
    this.setCache(STORAGE_KEYS.SETTINGS, data, CACHE.SETTINGS_TTL)
  }

  /**
   * 获取系统设置缓存
   */
  static getSettingsCache<T>(): T | null {
    return this.getCache<T>(STORAGE_KEYS.SETTINGS)
  }

  /**
   * 清理过期缓存
   */
  static cleanExpiredCache(): void {
    try {
      const keys = Object.values(STORAGE_KEYS)
      keys.forEach(key => {
        if (!this.hasCache(key)) {
          localStorage.removeItem(key)
        }
      })
    } catch (error) {
      console.error('清理过期缓存失败:', error)
    }
  }

  /**
   * 获取缓存统计信息
   */
  static getCacheStats(): {
    totalKeys: number
    expiredKeys: number
    totalSize: number
  } {
    try {
      const keys = Object.values(STORAGE_KEYS)
      let totalKeys = 0
      let expiredKeys = 0
      let totalSize = 0

      keys.forEach(key => {
        const cached = localStorage.getItem(key)
        if (cached) {
          totalKeys++
          totalSize += cached.length

          try {
            const cacheData = JSON.parse(cached)
            if (Date.now() - cacheData.timestamp > cacheData.ttl) {
              expiredKeys++
            }
          } catch {
            expiredKeys++
          }
        }
      })

      return {
        totalKeys,
        expiredKeys,
        totalSize
      }
    } catch (error) {
      console.error('获取缓存统计失败:', error)
      return {
        totalKeys: 0,
        expiredKeys: 0,
        totalSize: 0
      }
    }
  }
}
